import { computed, defineComponent, inject, nextTick, onMounted, reactive, ref } from "vue";
import { useStore as useAnalysisStore } from "@/store/analysis";
import styles from "./ResetLyrics.module.less";
import 'vue-json-pretty/lib/styles.css';
import _ from "lodash";
import { EditOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  props: {
    modify: {
      default: false,
    }
  },
  setup(props, { expose }) {
    const isEdit = ref(false);
    const analysisStore = useAnalysisStore();
    const result = ref({
      lyricsOri: [] as any[],
      temp: 0,
      beat: 0,
      lyrics: [] as any[],
    })
    const fetchData: any = inject("fetchData");
    const doRest = () => {
      result.value.lyrics.forEach(x => {
        x.forEach(y => {
          if (!y.word && y.choose && !y.changed) {
            y.hasRest = 1;
          }
        })
      })
    }
    onMounted(() => {
      // 编辑模式直接进入拉取到数据
      if (fetchData.lyricsData) {
        result.value.lyrics = fetchData.lyricsData?.lyrics || [];
        const _temp = fetchData.lyricsData?.temp;
        result.value.beat = fetchData.lyricsData?.beat || 0;
        result.value.temp = (_temp && Number(_temp) > 0) ? Number((60 / (Number(_temp) / 1000000)).toFixed(0)) : 0;
        result.value.lyricsOri = fetchData.lyricsData?.lyrics;
        doRest();
        return;
      }
      const _temp = analysisStore.result.temp;
      result.value.temp = (_temp && Number(_temp) > 0) ? Number((60 / (Number(_temp) / 1000000)).toFixed(0)) : 0;
      result.value.beat = analysisStore.result.beat;
      let arr: any[] = [];
      analysisStore.result.lyrics.forEach((x, idx: number) => {
        // 第一个打了换行符不进行换行
        if (x.breakLine === 1 && idx > 0) {
          result.value.lyrics.push(_.cloneDeep(arr));
          arr = [];
        }
        arr.push(x);
      })
      // 分割符剩下的剩余歌词
      if (arr.length > 0) {
        result.value.lyrics.push(_.cloneDeep(arr));
      }
      doRest();
      result.value.lyricsOri = result.value.lyrics;
    })
    const resetRow = (groupIdx: number, itemIdx: number) => {
      if (itemIdx === 0) {
        return;
      }
      const nLyrics = result.value.lyrics[groupIdx].slice(itemIdx - result.value.lyrics[groupIdx].length);
      result.value.lyrics[groupIdx].splice(itemIdx, result.value.lyrics[groupIdx].length - itemIdx);
      result.value.lyrics.splice(groupIdx + 1, 0, nLyrics);
    }
    const rebackRow = (groupIdx: number, itemIdx: number) => {
      if (itemIdx !== 0) {
        return;
      }
      const nLyrics = result.value.lyrics[groupIdx];
      result.value.lyrics[groupIdx - 1] = result.value.lyrics[groupIdx - 1].concat(nLyrics);
      result.value.lyrics.splice(groupIdx, 1);
    }
    const getResult = () => {
      return {
        temp: ((60 / result.value.temp) * 1000000).toFixed(0),
        beat: result.value.beat,
        lyrics: result.value.lyrics,
      };
    }
    // 填入歌词弹窗状态
    const setLyricsState = reactive({
      visible: false,
      content: null,
    })
    // 打开歌词填入弹窗
    const openSetLyrics = () => {
      setLyricsState.visible = true;
    }
    // 填词
    const setLyricsConfirm = async () => {
      const lyricsOri = _.cloneDeep(result.value.lyricsOri);
      const content = _.cloneDeep(setLyricsState.content);
      let content3d: any[] = [];
      content?.split?.("\n")?.forEach((x: string, idx: number) => {
        if (x) {
          let arr1: any[] = [];
          x.trim().split(" ").join("").split("").forEach((y: string) => {
            arr1.push({
              word: y,
            });
          })
          content3d.push({
            line: idx + 1,
            words: arr1,
          });
        }
      })
      let words: any[] = [];
      content3d.forEach((x, idxX) => {
        x.words.forEach((y, idxY) => {
          words.push({
            word: y.word,
            isCut: idxX !== 0 && idxY === 0,
          })
        })
      })
      let lyrics: any[] = [];
      let count = 0;
      let wordsLen = words.length;
      let arr: any[] = [];
      lyricsOri.forEach((t, idt) => {
        t.forEach((x, idx) => {
          if (x.word) {
            if (count === 0 && (idt !== 0 || idx !== 0)) {
              lyrics.push(_.cloneDeep(arr));
              arr = [];
            }
            if (count < wordsLen) {
              const word2 = words.shift();
              if (word2?.word && x.word !== word2?.word) {
                x.errWord = word2?.word;
                x.successWord = x.word;
              }
              if (word2?.isCut) {
                lyrics.push(_.cloneDeep(arr));
                arr = [];
              }
            }
            arr.push(x);
            count++;
          } else {
            arr.push(x);
          }
        })
        if (count >= wordsLen) {
          lyrics.push(_.cloneDeep(arr));
          arr = [];
        }
      })
      result.value.lyrics = lyrics;
      setLyricsState.visible = false;
    }
    // 校对
    const setLyricsConfirm2 = async () => {
      let content = _.cloneDeep(setLyricsState.content);
      content = content.replaceAll('\\', '');
      content = content.replaceAll('/', '');
      let content3d: any[] = [];
      content?.split?.("\n")?.forEach((x: string, idx: number) => {
        if (x) {
          let arr1: any[] = [];
          x.trim().split(" ").join("").split("").forEach((y: string) => {
            arr1.push({
              word: y,
            });
          })
          content3d.push({
            line: idx + 1,
            words: arr1,
          });
        }
      })
      let words: any[] = [];
      content3d.forEach((x) => {
        x.words.forEach((y) => {
          words.push({
            word: y.word,
          })
        })
      })
      let count = 0;
      let wordsLen = words.length;
      result.value.lyrics.forEach((t, idt) => {
        t.forEach((x, idx) => {
          if (x.word) {
            if (count < wordsLen) {
              const word2 = words.shift();
              if (word2?.word && x.word !== word2?.word) {
                x.errWord = word2?.word;
                x.successWord = x.word;
              } else {
                delete x.errWord;
                delete x.successWord;
              }
            }
            count++;
          }
        })
      })
      setLyricsState.visible = false;
      floatCheckBtnShow.value = true;
    }
    expose({
      getResult,
    })

    const hasRepeatWord = computed(() => {
      return result.value.lyrics.some(x => x.some(y => y.repeatWord));
    })

    const floatCheckBtnShow = ref(false);

    // 歌词
    const Word = (props: any) => {
      return <>
        <a-input style={{ display: (isEdit.value && !props.item.hasRest) ? "flex" : "none" }} class={[styles.lyrics, styles.input, props.item.choose && styles.hasChoose, props.item.errWord && styles.hasErr, props.item.repeatWord && styles.repeatWord]} v-model:value={props.item.word} onChange={(e) => { props.item.errWord = null; props.item.successWord = null; props.item.changed = 1; }} />
        <div style={{ display: (!isEdit.value || props.item.hasRest) ? "flex" : "none" }} class={[styles.lyrics, props.item.choose && styles.hasChoose, props.item.errWord && styles.hasErr, props.item.repeatWord && styles.repeatWord]} onDblclick={() => { resetRow(props.groupIdx, props.itemIdx) }}>{props.item.word ? props.item.word : props.item.choose}</div>
      </>
    }
    return () => (
      <>
        {
          props.modify && <>
            <div class={styles.step}>
              <div class={styles['step-flag']}>修改速度</div>
            </div>
            <div class={styles['step-content']}>
              <a-input-number style="width:300px;" placeholder="请填写曲谱速度" v-model:value={result.value.temp} />
            </div>
          </>
        }
        <div class={styles.step}>
          <div class={styles['step-flag']}>歌词排版</div>
        </div>
        {
          hasRepeatWord.value && <a-alert style={{ marginTop: "20px" }} message="当前曲谱歌词存在自动查找匹配情况，请注意橙色边框文字" type="warning" />
        }
        <div class={styles.resetLyrics}>
          {
            result.value.lyrics.map((group: any, groupIdx: number) => (
              <div class={[styles.lyricsGroupBox, group.length > 15 && styles.tooMoreLyrics]} title={group.length > 15 ? "歌词太多了!" : ""}>
                {
                  group.map((item: any, itemIdx: number) => (
                    <div class={styles.lyricsBox}>
                      <a-dropdown trigger="contextmenu" placement="bottomRight" v-slots={{
                        overlay: () => <>
                          <a-menu>
                            <a-menu-item key="1" onClick={() => { resetRow(groupIdx, itemIdx) }}>换行</a-menu-item>
                            <a-menu-item key="2" onClick={() => { rebackRow(groupIdx, itemIdx) }}>删除换行</a-menu-item>
                          </a-menu>
                        </>
                      }}>
                        <div>
                          {
                            item.errWord ?
                              <a-tooltip title={<div style={{ display: "flex", alignItems: "center" }}><span>{`是否替换为: "${item.errWord === item.word ? item.successWord : item.errWord}"`}</span><a-button style={{ marginLeft: "10px" }} type="primary" size="small" onClick={() => { item.word = item.errWord === item.word ? item.successWord : item.errWord }}>确认</a-button></div>} color="red">
                                <div>
                                  <Word item={item} groupIdx={groupIdx} itemIdx={itemIdx} />
                                </div>
                              </a-tooltip>
                              :
                              <Word item={item} groupIdx={groupIdx} itemIdx={itemIdx} />
                          }
                        </div>
                      </a-dropdown>
                    </div>
                  ))
                }
              </div>
            ))
          }
        </div >
        {
          floatCheckBtnShow.value && <div class={styles.floatCheckBtn} onClick={() => { setLyricsConfirm2() }}>继续校对</div>
        }
        <div class={styles.suspendBtns}>
          <a-button shape="round" size="large" class={styles.setLyricsBtn}
            onClick={() => { openSetLyrics() }}>填词</a-button>
          <a-tooltip placement="topLeft" v-slots={{ title: () => <span>编辑歌词</span> }}>
            <a-button shape="circle" size="large" class={styles.isEditBtn} type={isEdit.value ? "primary" : "default"} v-slots={{
              icon: () => <EditOutlined />
            }} onClick={() => { isEdit.value = !isEdit.value }}></a-button>
          </a-tooltip>
        </div>
        <a-modal v-model:visible={setLyricsState.visible} title="填入歌词" v-slots={{
          footer: () => (
            <>
              <a-button type="primary" onClick={() => { setLyricsConfirm() }}>填词</a-button>
              <a-button type="primary" onClick={() => { setLyricsConfirm2() }}>校对</a-button>
            </>
          )
        }}>
          <a-textarea style={{ minHeight: "350px" }} v-model:value={setLyricsState.content} placeholder="请填入歌词,换行使用回车" />
        </a-modal>
      </>
    )
  }
})